// The payment page
// ================

define(['zepto', 'utils', 'wxupload', 'cityPicker'], function($, utils, wxupload) {
  return {

    init: function(data) {
      
      this.bindQrcodeUpload(data.jsConfig);
      
      this.bindSexSelect();
      
      this.bindMarriageSelect();
      
      this.bindCountrySelect();
      
      this.bindPCDSelect();

      this.bindSubmitAction();

    },

    bindQrcodeUpload : function(config) {

      var uploadButtin = $("a.upload-image"),
          that = this;
      $(document).on('click', '.checkbox,.radio', function(e){
        $(this).children("input").prop("checked", !$(this).children("input").prop("checked"));
      })
      
      wxupload.injectConfig(config)
      
      uploadButtin.on('click', function(e){
        
        wxupload.invokeUpload(

          function(localId) {
            $(".upload-image").text("已选择，可点击重新选择");
          },
          
          function(mediaId) {
            $('input[name="mediaId"]').val(mediaId);
          }
        )
        
      })

    },

    // saveQrcode: function(mediaId, orderId) {
    //   $.showPreloader('正在上传图片')
    //   var that = this
    //   $.ajax({
    //     type: 'GET',
    //     url: __CTX__.root + '/user-qrcode',
    //     data: {
    //       'order': orderId,
    //       'media': mediaId
    //     }
    //   }).done(
    //     function(response) {
    //       $.hidePreloader()
    //       utils.processResult(response, function(result) {
    //         $.toast(result.message || '上传二维码成功')
    //         $('input[name="qrcodePath"]').val(result.data.imagePath)
    //       }, function(result) {
    //         $.toast(result.message || '上传二维码失败')
    //       })
    //     }
    //   )
    // },
    
    bindSexSelect: function(sites) {
        
      that = this
      
      var $sexSelector = $("input[name='sexSelector']")
      
      $sexSelector.picker({
        toolbarTemplate: '<header class="bar bar-nav">\
                            <button class="button button-link pull-right close-picker">确定</button>\
                            <h1 class="title">请选择性别</h1>\
                         </header>',
        cols: [
          {
            textAlign: 'center',
            values: ['MALE', 'FEMALE'],
            displayValues: ['男', '女']
          }
        ],
        formatValue: function (picker, value, displayValue){
          $(this.input).next().val(value)
          return displayValue
        }
      });
      
    },
    
    bindMarriageSelect: function(sites) {
      
      that = this
      
      var $marriageSelector = $("input[name='marriageSelector']")
      
      $marriageSelector.picker({
        toolbarTemplate: '<header class="bar bar-nav">\
                            <button class="button button-link pull-right close-picker">确定</button>\
                            <h1 class="title">请选择婚姻状况</h1>\
                         </header>',
        cols: [
          {
            textAlign: 'center',
            values: ['UNMARRIED', 'MARRIED'],
            displayValues: ['未婚', '已婚']
          }
        ],
        formatValue: function (picker, value, displayValue){
          $(this.input).next().val(value)
          return displayValue
        }
      });
      
    },
    
    bindCountrySelect: function(sites) {
        
        that = this
        
        var $countrySelector = $("input[name='countrySelector']")
        
        $countrySelector.picker({
          toolbarTemplate: '<header class="bar bar-nav">\
                              <button class="button button-link pull-right close-picker">确定</button>\
                              <h1 class="title">请选择国家</h1>\
                           </header>',
          cols: [
            {
              textAlign: 'center',
              values: ['CHINA', 'OTHER'],
              displayValues: ['中国', '其他']
            }
          ],
          formatValue: function (picker, value, displayValue){
            $(this.input).next().val(value)
            if(value == 'OTHER') {
              $(".pcd-select").addClass("hide");
            }else {
              $(".pcd-select").removeClass("hide");
            }
            return displayValue
          }
        });
        
      },
    
    bindPCDSelect: function() {
        
        that = this
        
        var $marriageSelector = $("input[name='pcdSelector']")
        
        $marriageSelector.cityPicker({
          toolbarTemplate: '<header class="bar bar-nav">\
                              <button class="button button-link pull-right close-picker">确定</button>\
                              <h1 class="title">请选择省市区</h1>\
                           </header>',
         formatValue: function (picker, value, displayValue){
             $(this.input).next().val(value)
             return displayValue
           }
        });
    },

    // order submit evvent handler
    bindSubmitAction: function() {
      
      var thatSubmit = this
      
      var submitButton = $("a.button-submit")
      
      submitButton.on('click', function(e){
        e.preventDefault()
        // init all data
        var data = thatSubmit.onInitData()
        // validate all input
        if(thatSubmit.onValidateData(data)) {
          // do submit order with data
          data = thatSubmit.onAppendData(data)
          thatSubmit.onSubmitOrder(data)
        }
      })
      
    },

    // init data
    onInitData: function() {
      return {
        'investigationId': {
          'value': $('input[name="investigationId"]').val().trim(),
          'message': '调查号不能为空'
        },
        '_method': {
          'value': $('input[name="_method"]').val().trim(),
          'message': '请求方式不能为空'
        },
        // 'mediaId': {
        //   'value': $('input[name="mediaId"]').val().trim(),
        //   'message': '请上传微信二维码'
        // },
        'height': {
          'value': $('input[name="height"]').val().trim(),
          'message': '身高不能为空'
        },
        'weight': {
          'value': $('input[name="weight"]').val().trim(),
          'message': '请填写体重'
        },
        'age': {
          'value': $('input[name="age"]').val().trim(),
          'message': '请填写年龄'
        },
        'wechatNumber': {
          'value': $('input[name="wechatNumber"]').val().trim(),   
          'message': '手机号不能为空'
        },
        'email': {
            'value': $('input[name="email"]').val().trim(),
            'message': '请填写邮箱'
        },
        'marriage': {
          'value': $('input[name="marriage"]').val().trim(),   
          'message': '婚姻状况不能为空'
        },
        'sex': {
          'value': $('input[name="sex"]').val().trim(),   
          'message': '性别不能为空'
        },
        'countryEnum': {
            'value': $('input[name="countryEnum"]').val().trim(),   
            'message': '国家不能为空'
        },
        'location': {
          'value': $('textarea[name="location"]').val().trim(),   
          'message': '邮寄地址不能为空'
        }
      }
    },

    onValidateData: function(data) {
      var valid = _.find(data, function(item) {
        return !item.value
      })

      if (!!valid) return $.toast(valid.message)
      
      var email = data.email.value;
      var emailRe = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
      if(!emailRe.test(email)) {
        $.toast("请输入正确的邮箱格式")
        return false
      }
      
      var country = $('input[name="country"]').val()
      
      if(country == 'CHINA') {
        var pcd = $('input[name="pcd"]').val();
        if(!pcd) {
          $.toast("请选择省市区")
          return false;
        }
      }
      
      return true
    },

    onAppendData: function(data) {
      
      var expectations = $('textarea[name="expectations"]').val();
      
      expectations = expectations + $("input[name = 'diseaseDescriptionInput']").val();

      data.expectations = {
        'value': expectations
      }

      data.source = {
        'value': $('input[name="source"]:checked').val()
      }

      var checkedValues = $('input[name="diseaseDescriptionCheckbox"]:checked').map(function() {
        return this.value;
      }).get()

      var diseaseDescription = checkedValues.join("&nbsp;&nbsp;");
      
      data.diseaseDescription = {
        'value': diseaseDescription
      }
      
      var pcd = $("input[name='pcd']").val();
      
      if(pcd) {
        data.pcd = {
         'value': pcd
        }
      }
      
      return data;
    },

    onSubmitOrder: function(data) {

      $.showPreloader('正在提交')

      var processedData = _.mapObject(data, function(obj) {
        return obj.value
      })
      $.ajax({
        type: 'POST',
        url: __CTX__.root + '/profile/investigation',
        data: processedData
      }).done(function(response) {
        $.hidePreloader()
        utils.processResult(response, function(result) {
          $.toast('填写调查表成功')
          setTimeout(function() {
            window.location.href = __CTX__.root + '/profile/info'
          }, 1000)
        }, function(result) {
          $.toast(result.message || '填写调查表失败')
        })
      })
      
    }

  }
})